import React, { useEffect, useMemo, useRef, useState } from 'react';
import styles from './index.less';
import classnames from 'classnames';

export const TJTextField = (props) => {
  const { label = '', onChange, type = 'text', suffix, style = {} } = props;

  const inputRef = useRef(null);

  const [isFocus, setIsFocus] = useState(false);

  const [value, setValue] = useState('');

  useEffect(() => {
    setValue(props?.value || '');
  }, [props?.value]);

  const changeIsFocus = (value) => {
    setIsFocus(value);
  };

  const valueChange = (e) => {
    setValue(e.target.value);
    onChange?.(e);
  };

  const onAnimationStart = () => {
    changeIsFocus(true);
  };

  const handleFocus = (e) => {
    changeIsFocus(true);
    props?.onFocus?.(e);
  };

  const handleBlur = (e) => {
    changeIsFocus(false);
    props?.onBlur?.(e);
  };

  const _getLabel = () => (
    <div
      className={classnames(
        styles.labelBase,
        isFocus || !!value ? styles.labelTop : styles.labelCenter,
      )}
    >
      {label}
    </div>
  );

  return (
    <div className={styles.box} style={style}>
      {useMemo(() => _getLabel(), [label, isFocus, value])}
      <input
        ref={inputRef}
        type={type}
        className={classnames('MuiInputBase-input', styles.input)}
        value={value}
        onFocus={handleFocus}
        onBlur={handleBlur}
        onAnimationStart={onAnimationStart}
        onChange={valueChange}
      />
      <div className={styles.suffix}>{suffix && suffix}</div>
    </div>
  );
};
